//
//  RegisterViewController.m
//  JackDeve
//
//  Created by apple on 17/5/9.
//  Copyright © 2017年 wkq. All rights reserved.
//

#import "RegisterViewController.h"

@interface RegisterViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    RegisterView * v;
    NSDictionary * dic;
    NSDictionary * dic1;
}
//数据列表
@property (nonatomic, strong) UITableView *tabView;
//弹出验证码
@property (nonatomic, strong) XDCodePopView *codePopView;
//倒计时总时长
@property (nonatomic, assign) int secondsCountDown;

//定时器
@property (nonatomic, strong) NSTimer *countDownTimer;
@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =[UIColor whiteColor];
    //创建一个添加按钮
    UIButton *navLeftBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 5, 20, 20)];
    [navLeftBtn setBackgroundImage:[UIImage imageNamed:@"左箭头"] forState:UIControlStateNormal];
    [navLeftBtn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:navLeftBtn];
    
    v =[[RegisterView alloc]initWithFrame:self.view.frame];
    self.view =v;
    v.table.delegate = self;
    v.table.dataSource = self;
    
    self.title =@"注册";
}
//返回方法
-(void)click
{
  [self.navigationController popViewControllerAnimated:YES];
}

//返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}


//单元格内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellID = [NSString stringWithFormat:@"%@%ld%ld",@"XDTextFieldTableViewCellID",indexPath.section, indexPath.row];
    XDTextFieldTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        
        cell = [[XDTextFieldTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textField.secureTextEntry = NO;
    }
    
    if (indexPath.row == 0) {
        
        cell.textField.tag = 10;
        cell.textField.delegate=self;
        cell.textField.placeholder = @"输入手机号";
        cell.textField.leftView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon1_11"]];
        cell.textField.leftViewMode = UITextFieldViewModeAlways;
        cell.textField.keyboardType = UIKeyboardTypeNumberPad;
    }
    else if (indexPath.row == 2)
    {
        cell.textField.tag = 12;
        cell.textField.delegate=self;
        cell.textField.placeholder = @"输入密码";
        cell.textField.leftView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon1_11"]];
        cell.textField.leftViewMode = UITextFieldViewModeAlways;
       
    }
    else if (indexPath.row == 1)
    {
        static NSString *codeCellID = @"XDTextFeildCodeTableViewCellID";
        XDTextFeildCodeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:codeCellID];
        if (!cell) {
            
            cell = [[XDTextFeildCodeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:codeCellID];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textField.tag = 11;
            cell.textField.leftView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon10_03"]];
            cell.textField.delegate=self;
            cell.textField.leftViewMode = UITextFieldViewModeAlways;
            [cell.codeBtn addTarget:self action:@selector(codeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            cell.codeBtn.tag=21;
          
        }
        
        return cell;
    }
    
    
    return cell;
}


//获取验证码
- (void)codeBtnClick:(UIButton *)btn
{
    UITextField *phoneNumberTextField = [v.table viewWithTag:10];
    
    BOOL isPhoneNumber = [XDTools isMobileNumber:phoneNumberTextField.text];
    
    if (isPhoneNumber) {
        
        NSLog(@"手机号正确");
        
        [self MessageCodeHttp];
    }
    else
    {
        [self.view makeToast:@"请输入正确的手机号码" duration:0.5f position:CSToastPositionCenter];
    }
}

//获取短信验证码请求
- (void)MessageCodeHttp
{
    UITextField *phoneNumberTextField = [v.table viewWithTag:10];
//    系统自带
    
         NSString *str = [[NSString stringWithFormat:Send1,phoneNumberTextField.text] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSURL * url =[NSURL URLWithString:str];
    
        NSURLSession * session =[NSURLSession sharedSession];
        //数据任务
        NSURLSessionDataTask * task =[session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    
    
            dic =[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
       
             [self MessageCodeHttpFinish];
    
    
        }];
    
        [task resume];
    
}

- (void)MessageCodeHttpFinish
{
   
    
    if ([[dic objectForKey:@"errmsg"] isEqualToString:@"验证码发送成功"]) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UIButton *codeBtn = [v.table viewWithTag:21];
            
            codeBtn.userInteractionEnabled = NO;
            
            codeBtn.alpha = 0.4;
              [self timer];
        });
      
        
        [self.view makeToast:@"获取短信验证码成功" duration:0.5f position:CSToastPositionCenter];
        
    }
    else
    {
        [_codePopView.contentView makeToast:[dic objectForKey:@"ResultDesc"] duration:0.5f position:CSToastPositionCenter];
    }
}

//计时器
- (void)timer
{
    //设置倒计时总时长
    _secondsCountDown = 60;//60秒倒计时
    //开始倒计时
    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES]; //启动倒计时后会每秒钟调用一次方法 timeFireMethod
    
    //设置倒计时显示的时间
    
    UIButton *codeBtn = [v.table viewWithTag:21];
    [codeBtn setTitle:[NSString stringWithFormat:@"已发送(%d)",_secondsCountDown] forState:UIControlStateNormal];
}

//倒计时
-(void)timeFireMethod{
    //倒计时-1
    _secondsCountDown--;
    
    UIButton *codeBtn = [v.table viewWithTag:21];
    
    //修改倒计时标签现实内容
    [codeBtn setTitle:[NSString stringWithFormat:@"已发送(%d)",_secondsCountDown] forState:UIControlStateNormal];    //当倒计时到0时，做需要的操作，比如验证码过期不能提交
    
    if(_secondsCountDown == 0){
        [_countDownTimer invalidate];
        codeBtn.userInteractionEnabled = YES;
        codeBtn.alpha = 1;
        [codeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    UITextField *phoneNumberTextField = [v.table viewWithTag:10];
    
    UITextField *newsPhoneNumberTextField = [v.table viewWithTag:12];
    
    if (textField == phoneNumberTextField || textField == newsPhoneNumberTextField) {
        
        BOOL isPhoneNumber = [XDTools isMobileNumber:textField.text];
        
        if (isPhoneNumber) {
            
            NSLog(@"手机号正确");
        }
        else
        {
            [self.view makeToast:@"请输入正确的手机号码" duration:0.5f position:CSToastPositionCenter];
        }
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return SCREEN_HEIGHT / 4;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 95 + SCREEN_HEIGHT / 16 * 2;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    XDLoginHeaderView *header = [[XDLoginHeaderView alloc]init];
    
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    XDRegisterFooderView *fooder = [[XDRegisterFooderView alloc]init];
    
    [fooder.registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    [fooder.registerBtn addTarget:self action:@selector(registerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [fooder.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [fooder.loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    return fooder;
}

//登录
- (void)loginBtnClick
{
    
    [self.navigationController popViewControllerAnimated:YES];
}
//注册按钮
- (void)registerBtnClick:(UIButton *)btn
{
    UITextField *phoneTextField = [v.table viewWithTag:10];
    
    UITextField *codeTextField = [v.table viewWithTag:11];
    
    UITextField *secore = [v.table viewWithTag:12];
    
    BOOL isPhoneNumber = [XDTools isMobileNumber:phoneTextField.text];
    
    if (isPhoneNumber) {
        
        NSLog(@"手机号正确");
        
        if (codeTextField.text.length != 0) {
            
            [self RegisterHttpPhoneNumber:phoneTextField.text  mima:secore.text VerificationCode:codeTextField.text];
            
            
        }
        else
        {
            [self.view makeToast:@"输入验证码" duration:0.5f position:CSToastPositionCenter];
        }
    }
    else
    {
        [self.view makeToast:@"请输入正确的手机号码" duration:0.5f position:CSToastPositionCenter];
    }
}


//注册请求

- (void)RegisterHttpPhoneNumber:(NSString *)phoneNumber  mima:(NSString*)mimaNumber VerificationCode:(NSString *)code
{
    
    [[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:[NSString stringWithFormat:registe,phoneNumber,mimaNumber,code]] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dic1 = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

        
        [self RegisterFinish];
        
    }] resume];
}

- (void)RegisterFinish
{
    
    if ([[dic1 objectForKey:@"errmsg"] isEqualToString:@"用户已经存在,注册失败"]) {
        
        //验证码输入正确之后才会判断是否为存在
     
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alet = [UIAlertController alertControllerWithTitle:@"提示" message:@"用户已经存在,注册失败" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *act1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            UIAlertAction *act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alet addAction:act1];
            [alet addAction:act2];
            [self presentViewController:alet animated:YES completion:nil];
        });
    }
    else if ([[dic1 objectForKey:@"errmsg"] isEqualToString:@"验证码错误"]) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alet = [UIAlertController alertControllerWithTitle:@"提示" message:@"验证码输入错误" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *act1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            UIAlertAction *act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alet addAction:act1];
            [alet addAction:act2];
            [self presentViewController:alet animated:YES completion:nil];
        });
   
    }
  
    else if([dic1 objectForKey:@"errmsg"] == nil)
    {
        NSLog(@"注册成功");
                NSLog(@"您的token:%@",[[dic1 objectForKey:@"data"] objectForKey:@"token"]);
                NSLog(@"您的账号:%@",[[dic1 objectForKey:@"data"] objectForKey:@"mobile"]);
                NSLog(@"您的用户名:%@",[[dic1 objectForKey:@"data"] objectForKey:@"user_name"]);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            
            UIAlertController *alet = [UIAlertController alertControllerWithTitle:@"提示" message:@"注册成功" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *act1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                
              [self.navigationController popViewControllerAnimated:YES];
                
                
                
            }];
            UIAlertAction *act2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alet addAction:act1];
            [alet addAction:act2];
            [self presentViewController:alet animated:YES completion:nil];
        });
        
    }
}
//隐藏键盘

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
    [v.table resignFirstResponder];
}




@end
